package com.two.lbms.interceptor;

import com.two.lbms.exceptions.NoLoginException;
import com.two.lbms.lzs.service.AdminService;
import com.two.lbms.service.UserService;
import com.two.lbms.utils.CookieUtil;
import com.two.lbms.utils.LoginUserUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author hjx
 * @version V1.0
 * @Date 2023/7/19 11:33
 */
@Slf4j
public class NoLoginInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取Cookie中的⽤户ID
        // Integer userId = LoginUserUtil.releaseUserIdFromCookie(request);
        String admin = CookieUtil.getCookieValue(request, "admin");
        log.info("admin : {}",admin);
        // 判断⽤户ID是否不为空，且数据库中存在对应的⽤户记录
        if (StringUtils.isBlank(admin) || null == userService.queryUserByName(admin)) {
            // 抛出 noLoginException对象
            log.info("抛出未登录异常" );
            // String contextPath = request.getContextPath();
            // response.sendRedirect(contextPath + "/login");
            throw new NoLoginException();
        }

        return true;
    }
}
